package tr.richfacesext.filter;

import java.io.IOException;
import java.util.Iterator;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tr.richfacesext.components.ComponentConstants;
import tr.richfacesext.components.imgviewer.ImgViewerConstants;
import tr.richfacesext.resourcemanagement.ResourceManager;

/**
 * 
 * @author mert
 *
 */
public class RichFacesExtResourceFilter implements Filter {

	private FilterConfig config;

	public void init(FilterConfig config) {
		this.config = config;
	}

	public FilterConfig getFilterConfig() {
		return config;
	}
	
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, javax.servlet.ServletException {
		HttpServletRequest req = (HttpServletRequest) request;

		if (req.getRequestURI().contains(ImgViewerConstants.IMAGEVIEWER_VIEW_ID)) {
 			chain.doFilter(request, response);
 			return;
		}
		
		RichFacesExtResponseWrapper wrapper = new RichFacesExtResponseWrapper((HttpServletResponse) response);
		chain.doFilter(request, wrapper);
		
		includeResources(req, response, wrapper);
	}	

	private void includeResources(HttpServletRequest req, ServletResponse response, RichFacesExtResponseWrapper wrapper) throws IOException{
		String resourceIncludes = "";

		for (Iterator iterator = ResourceManager.getResources().iterator(); iterator.hasNext();) {
			String resource = (String) iterator.next();
			
			String resourceInclude = "";

			if (resource.endsWith("js")) {
				resourceInclude = "<script type=\"text/javascript\" src=\""
						+ req.getContextPath() + ComponentConstants.FACES_PREFIX + ComponentConstants.RICHFACESEXT_RESOURCE_LOADER_VIEW_ID
						+ resource + "\"></script>";
			} 
			else if (resource.endsWith("css")) {
				resourceInclude = "<link type=\"text/css\" rel=\"stylesheet\" href=\""
					+ req.getContextPath() + ComponentConstants.FACES_PREFIX + ComponentConstants.RICHFACESEXT_RESOURCE_LOADER_VIEW_ID
					+ resource + "\"></link>";
			}

			resourceIncludes += resourceInclude + "\n";
		}

		//TODO
		// what if head does not exist
		String responseContent = wrapper.toString();
		responseContent = responseContent.replace("<head>", "<head>" + resourceIncludes);

		response.getWriter().write(responseContent);

		ResourceManager.clearResources();
	}
	
	public void destroy() {
		config = null;
	}
}